package cb.com.etcdemo.util;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.Context;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.telephony.TelephonyManager;
import android.util.Base64;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Adapter;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;


import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.RandomAccessFile;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 此类为一工具类，包含了各种常用共用方法 1、将文件转为Base64字符串 2、将Bitmap转为Base64字符串 3、保存Bitmap到文件
 * 4、将日期转换为一定格式的字符串 5、将一定格式的日期转换为毫秒数 6、显示提示信息 7、弹出警示对话框，并且有两个按钮 8、显示选择日期对话框到文本框中
 * 9、显示时间对话框 只显示时分秒 10、显示一个滚动进度条条对话框 11、关闭滚动进度条对话框 12、XXXX-XX-XX格式的日期字符串转成星期几
 * 13、XXXXX是否为手机号 14、XXXXX是否为邮箱
 * 15、计算两个日期天数16、滑轮组选择时间方法17、获取ARM时长18、拨打电话19、获取当前时间
 *
 * @author Administrator
 */
public class Tools {
    public static final String HTTP_ERROR = "网络不通，请重试！";
    // public static final String HTTP_ERROR = "网络不通，请查看您的网络环境再重试！";
    public static final String LOAD_ALL = "已经加载全部数据！";
    // 提示框
    public static ProgressDialog proDialog = null;

    // 判断网络连接
    public static boolean isConnected(Context activity) {
        try {
            if(activity != null){
                Context context = activity;
                // 获取手机所有连接管理对象（包括对wi-fi,net等连接的管理）
                ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
                if (connectivityManager == null){
                    return false;
                }else{
                    // 获取NetworkInfo对象
                    NetworkInfo[] networkInfo = connectivityManager.getAllNetworkInfo();
                    if (networkInfo != null && networkInfo.length > 0){
                        for (int i = 0; i < networkInfo.length; i++){
                            // 判断当前网络状态是否为连接状态
                            if (networkInfo[i].getState() == NetworkInfo.State.CONNECTED){
                                return true;
                            }
                        }
                    }
                }
            }else{
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }


    public static String format(String s) {
        String str = s
                .replaceAll(
                        "[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……& amp;*（）——+|{}【】‘；：”“’。，、？|-]",
                        "");
        return str;

    }
    //得到32位的uuid
    public static String getUUID32(){

        return UUID.randomUUID().toString().replace("-", "").toLowerCase();

    }

    /**
     * 把batmap 转file
     * @param bitmap
     * @param filepath
     */
    public static File saveBitmapFile(Bitmap bitmap, String filepath){
        File file=new File(filepath);//将要保存图片的路径
        try {
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
            bos.flush();
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file;
    }
    /**
     * 获取手机IMEI号
     */
    public static String getIMEI(Context context) {
        TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(context.TELEPHONY_SERVICE);
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return "";
        } else {
            String imei = telephonyManager.getDeviceId();
            return imei;
        }
    }

    /**
     * 获取手机IMSI号
     */
    public static String getIMSI(Context context) {
        TelephonyManager mTelephonyMgr = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.

            return "";
        } else {
            String imsi = mTelephonyMgr.getSubscriberId();
            return imsi;
        }
    }

    /**
     * 打开进度提示窗口
     */
    public static void showProgressDialog(Activity activity, String message) {
        if (null == proDialog) {
            proDialog = new ProgressDialog(activity);
            proDialog.setCanceledOnTouchOutside(false);
            proDialog.setCancelable(false);
            proDialog.setTitle("请稍候......");
            proDialog.setMessage(message);
        }
        if (!proDialog.isShowing()) {
            proDialog.show();
        }
    }

    public static void closeProgressDialog() {
        if (proDialog != null) {
            if (proDialog.isShowing()) {
                proDialog.dismiss();
            }
        }
    }

    // 保存文件到指定路径
    public static boolean saveImageToGallery(Context context, Bitmap bmp) {
        // 首先保存图片
        String storePath = Environment.getExternalStorageDirectory()
                .getAbsolutePath() + File.separator + "kaiqizhe";
        File appDir = new File(storePath);
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        String fileName = System.currentTimeMillis() + ".jpg";
        File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            // 通过io流的方式来压缩保存图片
            boolean isSuccess = bmp.compress(CompressFormat.JPEG, 60,
                    fos);
            fos.flush();
            fos.close();

            // 把文件插入到系统图库
            // MediaStore.Images.Media.insertImage(context.getContentResolver(),
            // file.getAbsolutePath(), fileName, null);

            // 保存图片后发送广播通知更新数据库
            Uri uri = Uri.fromFile(file);
            context.sendBroadcast(new Intent(
                    Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
            if (isSuccess) {
                return true;
            } else {
                return false;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    // 删除文件
    public static boolean delFile(String fileName) {
        File file = new File(fileName);
        if (file.isFile()) {
            file.delete();
        }
        return file.exists();
    }

    /**
     * 计算数据大小，将bit转换为k或M的单位输出
     *
     * @param dataSize
     * @return
     */
    public static String getApkSize(long dataSize) {
        long kb = dataSize / 1024; // 单位k
        if (kb < 1024) {
            return kb + "k";
        }
        double mb = dataSize / 1024.0 / 1024.0 + 0.05; // 转换为M，保留一位小数，四舍五入
        return new DecimalFormat(".0").format(mb) + "M";
    }


    /**
     * 验证身份证号是否符合规则
     *
     * @param text
     *            身份证号
     * @return
     */
    /**
     * 验证所有的身份证的合法性
     *
     * @param idcard
     *            身份证
     * @return 合法返回true，否则返回false
     */
    /**
     * <pre>
     * 省、直辖市代码表：
     *     11 : 北京  12 : 天津  13 : 河北       14 : 山西  15 : 内蒙古
     *     21 : 辽宁  22 : 吉林  23 : 黑龙江  31 : 上海  32 : 江苏
     *     33 : 浙江  34 : 安徽  35 : 福建       36 : 江西  37 : 山东
     *     41 : 河南  42 : 湖北  43 : 湖南       44 : 广东  45 : 广西      46 : 海南
     *     50 : 重庆  51 : 四川  52 : 贵州       53 : 云南  54 : 西藏
     *     61 : 陕西  62 : 甘肃  63 : 青海       64 : 宁夏  65 : 新疆
     *     71 : 台湾
     *     81 : 香港  82 : 澳门
     *     91 : 国外
     * </pre>
     */
    private static String cityCode[] = {"11", "12", "13", "14", "15", "21",
            "22", "23", "31", "32", "33", "34", "35", "36", "37", "41", "42",
            "43", "44", "45", "46", "50", "51", "52", "53", "54", "61", "62",
            "63", "64", "65", "71", "81", "82", "91"};

    /**
     * 每位加权因子
     */
    private static int power[] = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5,
            8, 4, 2};

    public static boolean isValidatedAllIdcard(String idcard) {
        if (idcard == null || "".equals(idcard)) {
            return false;
        }
        if (idcard.length() == 15) {
            return validate15IDCard(idcard);
        }
        return validate18Idcard(idcard);
        // String REGEX_ID_CARD = "(^\\d{15}$)|(^\\d{17}([0-9]|X)$)";
        // return Pattern.matches(REGEX_ID_CARD, idcard);

    }

    /**
     * <p>
     * 判断18位身份证的合法性
     * </p>
     * 根据〖中华人民共和国国家标准GB11643-1999〗中有关公民身份号码的规定，公民身份号码是特征组合码，由十七位数字本体码和一位数字校验码组成。
     * 排列顺序从左至右依次为：六位数字地址码，八位数字出生日期码，三位数字顺序码和一位数字校验码。
     * <p>
     * 顺序码: 表示在同一地址码所标识的区域范围内，对同年、同月、同 日出生的人编定的顺序号，顺序码的奇数分配给男性，偶数分配 给女性。
     * </p>
     * <p>
     * 1.前1、2位数字表示：所在省份的代码； 2.第3、4位数字表示：所在城市的代码； 3.第5、6位数字表示：所在区县的代码；
     * 4.第7~14位数字表示：出生年、月、日； 5.第15、16位数字表示：所在地的派出所的代码；
     * 6.第17位数字表示性别：奇数表示男性，偶数表示女性；
     * 7.第18位数字是校检码：也有的说是个人信息码，一般是随计算机的随机产生，用来检验身份证的正确性。校检码可以是0~9的数字，有时也用x表示。
     * </p>
     * <p>
     * 第十八位数字(校验码)的计算方法为： 1.将前面的身份证号码17位数分别乘以不同的系数。从第一位到第十七位的系数分别为：7 9 10 5 8 4
     * 2 1 6 3 7 9 10 5 8 4 2
     * </p>
     * <p>
     * 2.将这17位数字和系数相乘的结果相加。
     * </p>
     * <p>
     * 3.用加出来和除以11，看余数是多少
     * </p>
     * 4.余数只可能有0 1 2 3 4 5 6 7 8 9 10这11个数字。其分别对应的最后一位身份证的号码为1 0 X 9 8 7 6 5 4 3
     * 2。
     * <p>
     * 5.通过上面得知如果余数是2，就会在身份证的第18位数字上出现罗马数字的Ⅹ。如果余数是10，身份证的最后一位号码就是2。
     * </p>
     *
     * @param idcard
     * @return
     */
    public static boolean validate18Idcard(String idcard) {
        if (idcard == null) {
            return false;
        }

        // 非18位为假
        if (idcard.length() != 18) {
            return false;
        }
        // 获取前17位
        String idcard17 = idcard.substring(0, 17);

        // 前17位全部为数字
        if (!isDigital(idcard17)) {
            return false;
        }

        String provinceid = idcard.substring(0, 2);
        // 校验省份
        if (!checkProvinceid(provinceid)) {
            return false;
        }

        // 校验出生日期
        String birthday = idcard.substring(6, 14);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");

        try {
            Date birthDate = sdf.parse(birthday);
            String tmpDate = sdf.format(birthDate);
            if (!tmpDate.equals(birthday)) {// 出生年月日不正确
                return false;
            }

        } catch (ParseException e1) {

            return false;
        }

        // 获取第18位
        String idcard18Code = idcard.substring(17, 18);

        char c[] = idcard17.toCharArray();

        int bit[] = converCharToInt(c);

        int sum17 = 0;

        sum17 = getPowerSum(bit);

        // 将和值与11取模得到余数进行校验码判断
        String checkCode = getCheckCodeBySum(sum17);
        if (null == checkCode) {
            return false;
        }
        // 将身份证的第18位与算出来的校码进行匹配，不相等就为假
        if (!idcard18Code.equalsIgnoreCase(checkCode)) {
            return false;
        }

        return true;
    }

    /**
     * 校验15位身份证
     * <p>
     * <pre>
     * 只校验省份和出生年月日
     * </pre>
     *
     * @param idcard
     * @return
     */
    public static boolean validate15IDCard(String idcard) {
        if (idcard == null) {
            return false;
        }
        // 非15位为假
        if (idcard.length() != 15) {
            return false;
        }

        // 15全部为数字
        if (!isDigital(idcard)) {
            return false;
        }

        String provinceid = idcard.substring(0, 2);
        // 校验省份
        if (!checkProvinceid(provinceid)) {
            return false;
        }

        String birthday = idcard.substring(6, 12);

        SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd");

        try {
            Date birthDate = sdf.parse(birthday);
            String tmpDate = sdf.format(birthDate);
            if (!tmpDate.equals(birthday)) {// 身份证日期错误
                return false;
            }

        } catch (ParseException e1) {

            return false;
        }

        return true;
    }

    /**
     * 将15位的身份证转成18位身份证
     *
     * @param idcard
     * @return
     */
    public static String convertIdcarBy15bit(String idcard) {
        if (idcard == null) {
            return null;
        }

        // 非15位身份证
        if (idcard.length() != 15) {
            return null;
        }

        // 15全部为数字
        if (!isDigital(idcard)) {
            return null;
        }

        String provinceid = idcard.substring(0, 2);
        // 校验省份
        if (!checkProvinceid(provinceid)) {
            return null;
        }

        String birthday = idcard.substring(6, 12);

        SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd");

        Date birthdate = null;
        try {
            birthdate = sdf.parse(birthday);
            String tmpDate = sdf.format(birthdate);
            if (!tmpDate.equals(birthday)) {// 身份证日期错误
                return null;
            }

        } catch (ParseException e1) {
            return null;
        }

        Calendar cday = Calendar.getInstance();
        cday.setTime(birthdate);
        String year = String.valueOf(cday.get(Calendar.YEAR));

        String idcard17 = idcard.substring(0, 6) + year + idcard.substring(8);

        char c[] = idcard17.toCharArray();
        String checkCode = "";

        // 将字符数组转为整型数组
        int bit[] = converCharToInt(c);

        int sum17 = 0;
        sum17 = getPowerSum(bit);

        // 获取和值与11取模得到余数进行校验码
        checkCode = getCheckCodeBySum(sum17);

        // 获取不到校验位
        if (null == checkCode) {
            return null;
        }
        // 将前17位与第18位校验码拼接
        idcard17 += checkCode;
        return idcard17;
    }

    /**
     * 校验省份
     *
     * @param provinceid
     * @return 合法返回TRUE，否则返回FALSE
     */
    private static boolean checkProvinceid(String provinceid) {
        for (String id : cityCode) {
            if (id.equals(provinceid)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 数字验证
     *
     * @param str
     * @return
     */
    private static boolean isDigital(String str) {
        return str.matches("^[0-9]*$");
    }

    /**
     * 将身份证的每位和对应位的加权因子相乘之后，再得到和值
     *
     * @param bit
     * @return
     */
    private static int getPowerSum(int[] bit) {

        int sum = 0;

        if (power.length != bit.length) {
            return sum;
        }

        for (int i = 0; i < bit.length; i++) {
            for (int j = 0; j < power.length; j++) {
                if (i == j) {
                    sum = sum + bit[i] * power[j];
                }
            }
        }
        return sum;
    }

    /**
     * 将和值与11取模得到余数进行校验码判断
     *
     * @param sum17
     * @return 校验位
     */
    private static String getCheckCodeBySum(int sum17) {
        String checkCode = null;
        switch (sum17 % 11) {
            case 10:
                checkCode = "2";
                break;
            case 9:
                checkCode = "3";
                break;
            case 8:
                checkCode = "4";
                break;
            case 7:
                checkCode = "5";
                break;
            case 6:
                checkCode = "6";
                break;
            case 5:
                checkCode = "7";
                break;
            case 4:
                checkCode = "8";
                break;
            case 3:
                checkCode = "9";
                break;
            case 2:
                checkCode = "x";
                break;
            case 1:
                checkCode = "0";
                break;
            case 0:
                checkCode = "1";
                break;
        }
        return checkCode;
    }

    /**
     * 将字符数组转为整型数组
     *
     * @param c
     * @return
     * @throws NumberFormatException
     */
    private static int[] converCharToInt(char[] c) throws NumberFormatException {
        int[] a = new int[c.length];
        int k = 0;
        for (char temp : c) {
            a[k++] = Integer.parseInt(String.valueOf(temp));
        }
        return a;
    }

    // 获取mac地址
    public static String getMac() {
        String macSerial = "";
        try {
            Process pp = Runtime.getRuntime().exec(
                    "cat /sys/class/net/wlan0/address");
            InputStreamReader ir = new InputStreamReader(pp.getInputStream());
            LineNumberReader input = new LineNumberReader(ir);

            String line;
            while ((line = input.readLine()) != null) {
                macSerial += line.trim();
            }
            input.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return macSerial;
    }

    // 压缩
    public static void compress(String srcPath, Activity context) {
        DisplayMetrics dm = new DisplayMetrics();
        context.getWindowManager().getDefaultDisplay().getMetrics(dm);

        float hh = dm.heightPixels;
        float ww = dm.widthPixels;
        BitmapFactory.Options opts = new BitmapFactory.Options();
        opts.inJustDecodeBounds = true;
        Bitmap bitmap = BitmapFactory.decodeFile(srcPath, opts);
        opts.inJustDecodeBounds = false;
        int w = opts.outWidth;
        int h = opts.outHeight;
        int size = 0;
        if (w <= ww && h <= hh) {
            size = 1;
        } else {
            double scale = w >= h ? w / ww : h / hh;
            double log = Math.log(scale) / Math.log(2);
            double logCeil = Math.ceil(log);
            size = (int) Math.pow(2, logCeil);
        }
        opts.inSampleSize = size;
        bitmap = BitmapFactory.decodeFile(srcPath, opts);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int quality = 100;
        bitmap.compress(CompressFormat.JPEG, quality, baos);
        System.out.println(baos.toByteArray().length);
        while (baos.toByteArray().length > 45 * 1024) {
            baos.reset();
            bitmap.compress(CompressFormat.JPEG, quality, baos);
            quality -= 10;
            System.out.println(baos.toByteArray().length);
        }
        try {
            baos.writeTo(new FileOutputStream(srcPath));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                baos.flush();
                baos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 读取本地资源的图片
     *
     * @param context
     * @param resId
     * @return
     */
    public static Bitmap ReadBitmapById(Context context, int resId) {
        BitmapFactory.Options opt = new BitmapFactory.Options();
        opt.inPreferredConfig = Config.RGB_565;
        opt.inPurgeable = true;
        opt.inInputShareable = true;
        // 获取资源图片
        InputStream is = context.getResources().openRawResource(resId);
        return BitmapFactory.decodeStream(is, null, opt);
    }

    /**
     * 验证车牌号是否符合规则
     */
    public static boolean isBrandNumber(String brandnum) {
        // String regx="[\u4e00-\u9fa5]{1}[A-Z]{1}[A-Z_0-9]{5}";
        String regx = "[A-Z]{1}[A-Z_0-9]{5}"; // 因为项目中的车牌号归属地简称为必有项这里先不作判断
        return brandnum.matches(regx);
    }

    public static boolean isBrandNumberWithHeader(String brandnum) {
        String regx = "[\u4e00-\u9fa5]{1}[A-Z]{1}[A-Z_0-9]{5}";
        return brandnum.matches(regx);
    }

    // 写文件
    public static void writeSDFile(String fileName, String write_str)
            throws IOException {

        try {
            File file = new File(fileName);

            FileOutputStream fos = new FileOutputStream(file);
            byte[] content = Base64.decode(write_str, Base64.DEFAULT);

            // byte[] bytes = write_str.getBytes();

            fos.write(content);

            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 将文件转为Base64字符串
     *
     * @return
     * @throws Exception
     */
    public static String encodeBase64File(File file) throws Exception {
        FileInputStream inputFile = new FileInputStream(file);
        byte[] buffer = new byte[(int) file.length()];
        inputFile.read(buffer);
        inputFile.close();
        return Base64.encodeToString(buffer, Base64.DEFAULT);
    }

    // 读文件
    public static String FileToString(String filename) throws Exception {
        String res = "";
        try {
            File file = new File(filename);
            FileInputStream inputFile = new FileInputStream(file);
            byte[] buffer = new byte[inputFile.available()];
            inputFile.read(buffer);
            // res = EncodingUtils.getString(buffer, "UTF-8");
            res = Base64.encodeToString(buffer, Base64.NO_WRAP);
            inputFile.close();
            return res;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return res;
    }

    /**
     * 解密
     */
    public static String decryptBASE64(String str) {
        if (str == null || str.length() == 0) {
            return null;
        }
        try {
            byte[] encode = str.getBytes();
            // base64 解密
            return new String(Base64.decode(encode, 0, encode.length,
                    Base64.DEFAULT));

        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    /*
     * 把String 写回到SD 卡
     */
    public void writeFileSdcard(String fileName, String message) {

        try {

            // FileOutputStream fout = openFileOutput(fileName, MODE_PRIVATE);

            FileOutputStream fout = new FileOutputStream(fileName);

            byte[] bytes = message.getBytes();

            fout.write(bytes);

            fout.close();

        } catch (Exception e) {

            e.printStackTrace();

        }

    }

    /**
     * 将Bitmap转为Base64字符串
     *
     * @return
     * @throws Exception
     */
    public static String encodeBase64File(Bitmap bitmap) {
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();// outputstream
            // 将bitmap做成输出流，保证图片质量100%
            bitmap.compress(CompressFormat.PNG, 100, baos);
            // 转换成byte数组
            byte[] appicon = baos.toByteArray();// 转为byte数组
            // 以base64编码将byte数组转换成字符串
            return Base64.encodeToString(appicon, Base64.DEFAULT);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }

    /**
     * 将日期转换为一定格式的字符串
     *
     * @param date
     * @return
     */
    public static String DateFormat(Date date) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(date);
    }

    /**
     * 将一定格式的日期转换为毫秒数 如：Tools.StringDateToLong(startDate,"yyyy-MM-dd")
     *
     * @param date
     * @return
     * @throws ParseException
     */
    public static long StringDateToLong(String date, String format)
            throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.parse(date).getTime();// 毫秒
    }

    /**
     * 弹出警示对话框，并且有两个按钮
     *
     * @param c
     * 要弹出的页面
     * @param title
     * 标题内容
     * @param msg
     * 提示内容
     * @param neutralBtnText
     * 确定按钮内容
     * @param neutralBtnListen
     * 确定按钮触发的事件
     * @param egativeBtnText
     * 取消按钮内容
     * @param egativeBtnListen
     * 取消按钮触发的事件
     */
    static Dialog dialog;

    public static void showDialog(Context c, String title, String msg,
                                  String neutralBtnText, OnClickListener neutralBtnListen,
                                  String egativeBtnText, OnClickListener egativeBtnListen) {
        dialog = new AlertDialog.Builder(c).setTitle(title).setMessage(msg)
                .setNeutralButton(neutralBtnText, neutralBtnListen)
                .setNegativeButton(egativeBtnText, egativeBtnListen).show();

    }

    public static void closeDialog() {
        dialog.dismiss();
    }

	/*
     * 显示时间年-月-日 周几 -时分
	 */

    /**
     * 日期对话框
     */
    public static void dateDialog(final Context mContext) {
        Calendar c = Calendar.getInstance();
        DatePickerDialog dialog = new DatePickerDialog(mContext,
                new OnDateSetListener() {

                    @Override
                    public void onDateSet(DatePicker dp, int year, int month,
                                          int dayOfMonth) {
                        Toast.makeText(
                                mContext,
                                "" + year + "-" + (month + 1) + "-"
                                        + dayOfMonth, Toast.LENGTH_SHORT)
                                .show();

                        // showToast(year + "-" + (month + 1) + "-" +
                        // dayOfMonth);
                    }
                }, c.get(Calendar.YEAR), c.get(Calendar.MONTH),
                c.get(Calendar.DAY_OF_MONTH));
        dialog.show();
    }

    /**
     * 显示选择日期对话框到文本框中
     *
     * @param context
     * @param textView
     */
    public static void datePicker(Context context, final TextView textView) {
        Calendar c = Calendar.getInstance();

        // 日期对话框
        DatePickerDialog dialog = // 继承了AlertDialog
                new DatePickerDialog(context, new OnDateSetListener() {

                    // 回调函数
                    @Override
                    public void onDateSet(DatePicker view, int year, int monthOfYear,
                                          int dayOfMonth) {

                        textView.setText(year
                                + "-"
                                + ((monthOfYear + 1) < 10 ? "0" + (monthOfYear + 1)
                                : (monthOfYear + 1)) + "-"
                                + (dayOfMonth < 10 ? "0" + dayOfMonth : dayOfMonth));
                    }
                },// 回调
                        c.get(Calendar.YEAR), c.get(Calendar.MONTH),
                        c.get(Calendar.DAY_OF_MONTH));

        // 显示对话框
        dialog.show();
    }

    public static void datePicker2(Context context, final TextView textView) {
        Calendar c = Calendar.getInstance();

        // 日期对话框
        DatePickerDialog dialog = // 继承了AlertDialog
                new DatePickerDialog(context, new OnDateSetListener() {

                    // 回调函数
                    @Override
                    public void onDateSet(DatePicker view, int year, int monthOfYear,
                                          int dayOfMonth) {
                        String date = year
                                + "-"
                                + ((monthOfYear + 1) < 10 ? "0" + (monthOfYear + 1)
                                : (monthOfYear + 1)) + "-"
                                + (dayOfMonth < 10 ? "0" + dayOfMonth : dayOfMonth);
                        textView.setText(date + "," + showWeek(date));
                        textView.setPadding(0, 0, 0, 10);
                    }
                },// 回调
                        c.get(Calendar.YEAR), c.get(Calendar.MONTH),
                        c.get(Calendar.DAY_OF_MONTH));

        // 显示对话框
        dialog.show();
    }

    /**
     * 获取指定日后 后 dayAddNum 天的 日期
     *
     * @param day       日期，格式为String："2013-9-3";
     * @param dayAddNum 增加天数 格式为int;
     * @return
     */
    public static String getDateStr(String day, int dayAddNum) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Date nowDate = null;
        try {
            nowDate = df.parse(day);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Date newDate2 = new Date(nowDate.getTime() + dayAddNum * 24 * 60 * 60
                * 1000);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String dateOk = simpleDateFormat.format(newDate2);
        return dateOk;
    }

    /**
     * 显示时间对话框 只显示时分秒
     */
    public static void timePicker(Context context, final TextView textView) {
        Calendar c = Calendar.getInstance();
        TimePickerDialog d = new TimePickerDialog(context,
                new OnTimeSetListener() {

                    @Override
                    public void onTimeSet(TimePicker view, int hourOfDay,
                                          int minute) {

                        textView.setText((hourOfDay < 10 ? "0" + hourOfDay
                                : hourOfDay)
                                + ":"
                                + (minute < 10 ? "0" + minute : minute));
                    }
                }, // 回调函数
                c.get(Calendar.HOUR_OF_DAY), c.get(Calendar.MINUTE), true);
        d.show();
    }

    // public static ProgressDialog progressDialog;
    //
    // /**
    // * 显示一个滚动条对话框
    // * */
    // public static void showProgressDialog(Context context, String message) {
    // try {
    // if (progressDialog == null) {
    // progressDialog = ProgressDialog.show(context, null, message);
    // progressDialog.setCanceledOnTouchOutside(true);
    // // progressDialog.setCancelable(true);
    // } else if (progressDialog != null) {
    // if (!progressDialog.isShowing())
    // progressDialog.setMessage(message);
    // }
    // } catch (Exception e) {
    // // TODO Auto-generated catch block
    // e.printStackTrace();
    // }
    // }
    //
    // /**
    // * 关闭滚动对话框
    // */
    // public static void closeProgressDialog() {
    // try {
    // if (progressDialog != null && progressDialog.isShowing()) {
    // progressDialog.cancel();
    // progressDialog = null;
    // }
    // } catch (Exception e) {
    // // TODO Auto-generated catch block
    // e.printStackTrace();
    // }
    // }

    /**
     * XXXX-XX-XX格式的日期字符串转成星期几
     *
     * @param dateString
     * @return
     */
    public static String showWeek(String dateString) {
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = null;
        try {
            date = sf.parse(dateString);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        int weekofday = c.get(Calendar.DAY_OF_WEEK);
        String returnResault = "";
        switch (weekofday) {
            case 1:
                returnResault = "星期日";
                break;
            case 2:
                returnResault = "星期一";
                break;
            case 3:
                returnResault = "星期二";
                break;
            case 4:
                returnResault = "星期三";
                break;
            case 5:
                returnResault = "星期四";
                break;
            case 6:
                returnResault = "星期五";
                break;
            case 7:
                returnResault = "星期六";
                break;
        }
        return returnResault;
    }

    /**
     * 对返回的日期进行处理
     *
     * @param dateStr
     * @return
     */
    public static String DateStrToDateStr(String dateStr) {
        if (dateStr != null) {
            if (dateStr.length() > 18) {
                String date = dateStr.substring(0, 10);
                // String time = dateStr.substring(11, 19);
                // return date + " " + time;
                return date;
            } else {
                return dateStr;
            }
        } else {
            return "";
        }
    }

    /**
     * 判断是否为手机号
     *
     * @param mobiles
     * @return
     */
    public static boolean isMobileNO(String mobiles) {
        // Pattern p = Pattern
        // .compile("^((13[0-9])|(14[0-9])|(15[^4,\\D])|(18[0,0-9])|(17[0,0-9]))\\d{8}$");
        // Matcher m = p.matcher(mobiles);
        // return m.matches();
        if (11 == mobiles.length()) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 判断是否为邮箱地址
     *
     * @param email
     * @return
     */
    public static boolean isEmail(String email) {
        String str = "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$";
        Pattern p = Pattern.compile(str);
        Matcher m = p.matcher(email);

        return m.matches();
    }

    /**
     * 计算两个日期之间相差的天数
     *
     * @param date1
     * @param date2
     * @return
     */
    public static int daysBetween(Date date1, Date date2) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date1);
        long time1 = cal.getTimeInMillis();
        cal.setTime(date2);
        long time2 = cal.getTimeInMillis();
        long between_days = (time2 - time1) / (1000 * 3600 * 24);

        return Integer.parseInt(String.valueOf(between_days));
    }

    /**
     * 计算两个日期之间相差的天数
     *
     * @return
     */
    public static int daysBetween(long date1, long date2) {

        long between_days = (date2 - date1) / (1000 * 3600 * 24);

        return Integer.parseInt(String.valueOf(between_days));
    }

    /**
     * 处理五角星评分显示，裁剪图片
     *
     * @param bitmap
     * @param scor
     * @return
     */
    public static Bitmap cutBitmap(Bitmap bitmap, float scor) {
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        Bitmap bitmapResult = Bitmap.createBitmap(width, height,
                Config.ARGB_8888);

        // 创建画布
        Canvas canvas = new Canvas(bitmapResult);

        float w = scor / 5 * width;
        if (w == 0) {
            w += 1;
        }

        // 下面这句是关键,剪裁图片
        bitmap = Bitmap
                .createBitmap(bitmap, 0, 0, (int) w, height, null, false);
        // 将图片按照坐标0,0 去拼接到画布
        canvas.drawBitmap(bitmap, 0, 0, null);

        return bitmapResult;
    }

    /**
     * 获取当前应用程序的版本号
     */
    public static int getVersionCode(Context context) {
        int code = -1;
        PackageManager pm = context.getPackageManager();
        try {
            PackageInfo packinfo = pm.getPackageInfo(context.getPackageName(),
                    0);
            code = packinfo.versionCode;
            return code;
        } catch (NameNotFoundException e) {
            e.printStackTrace();
            return code;
        }
    }

    /**
     * 获取当前应用程序的版本名称
     */
    public static String getVersionName(Context context) {
        String st = "版本号错误";
        PackageManager pm = context.getPackageManager();
        try {
            PackageInfo packinfo = pm.getPackageInfo(context.getPackageName(),
                    0);
            String version = packinfo.versionName;
            return version;
        } catch (NameNotFoundException e) {
            e.printStackTrace();
            return st;
        }
    }

    /**
     * 获取AMR时长
     */
    public static long getAmrDuration(File file) throws IOException {
        long duration = -1;
        int[] packedSize = {12, 13, 15, 17, 19, 20, 26, 31, 5, 0, 0, 0, 0, 0,
                0, 0};
        RandomAccessFile randomAccessFile = null;
        try {
            randomAccessFile = new RandomAccessFile(file, "rw");
            long length = file.length();// 文件的长度
            int pos = 6;// 设置初始位置
            int frameCount = 0;// 初始帧数
            int packedPos = -1;
            byte[] datas = new byte[1];// 初始数据值
            while (pos <= length) {
                randomAccessFile.seek(pos);
                if (randomAccessFile.read(datas, 0, 1) != 1) {
                    duration = length > 0 ? ((length - 6) / 650) : 0;
                    break;
                }
                packedPos = (datas[0] >> 3) & 0x0F;
                pos += packedSize[packedPos] + 1;
                frameCount++;
            }
            duration += frameCount * 20;// 帧数*20
        } finally {
            if (randomAccessFile != null) {
                randomAccessFile.close();
            }
        }
        return duration;
    }

    // 16
    public static float pixelToDp(Context context, float val) {
        float density = context.getResources().getDisplayMetrics().density;
        return val * density;
    }
//
//	// 拨打电话
//	public static void CallUp(Context ct, String phone) {
//		// 用intent启动拨打电话
//		Intent intent = new Intent(Intent.ACTION_CALL,
//				Uri.parse("tel:" + phone));
//		ct.startActivity(intent);
//	}

    // 获取当前时间返回格式：年-月-日 时：秒
    public static String getDate() {
        Calendar c = Calendar.getInstance();
        String year = String.valueOf(c.get(Calendar.YEAR));
        String month = String.valueOf(c.get(Calendar.MONTH));
        String day = String.valueOf(c.get(Calendar.DAY_OF_MONTH));
        String hour = String.valueOf(c.get(Calendar.HOUR_OF_DAY));
        String mins = String.valueOf(c.get(Calendar.MINUTE));
        String m = String.valueOf(c.get(Calendar.SECOND));
        StringBuffer sbBuffer = new StringBuffer();
        sbBuffer.append(year + "-" + month + "-" + day + " " + hour + ":"
                + mins + ":" + m);
        return sbBuffer.toString();
    }

    // 检索周几
    @SuppressLint("SimpleDateFormat")
    public static String WeekDay(String day) throws Exception {
        // 判断用车时间是否为周末
        String weekday = "";
        Calendar cal = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        cal.setTime(sdf.parse(day));
        if (cal.get(Calendar.DAY_OF_WEEK) == Calendar.MONDAY) {
            weekday = "周一";
        } else if (cal.get(Calendar.DAY_OF_WEEK) == Calendar.TUESDAY) {
            weekday = "周二";
        } else if (cal.get(Calendar.DAY_OF_WEEK) == Calendar.WEDNESDAY) {
            weekday = "周三";
        } else if (cal.get(Calendar.DAY_OF_WEEK) == Calendar.THURSDAY) {
            weekday = "周四";
        } else if (cal.get(Calendar.DAY_OF_WEEK) == Calendar.FRIDAY) {
            weekday = "周五";
        } else if (cal.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY) {
            weekday = "周六";
        } else if (cal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
            weekday = "周日";
        }
        return weekday;
    }

    // 获取当前时间戳
    public static long GetTimeStamp() {
        return System.currentTimeMillis() / 1000;// 获取系统时间的10位的时间戳;
    }

    // 将时间戳转换成会时间
    public static String GetTime(String time) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long lcc_time = Long.valueOf(time);
        String re_StrTime = sdf.format(new Date(lcc_time * 1000L));
        return re_StrTime;
    }

    /**
     * 显示toast
     *
     * @param ctx
     * @param msg
     */
    public static void showToast(final Activity ctx, final String msg) {
        if (null != ctx) {
            // 判断是在子线程，还是主线程
            if ("main".equals(Thread.currentThread().getName())) {
                Toast.makeText(ctx, msg, Toast.LENGTH_LONG).show();
            } else {
                // 子线程
                ctx.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(ctx, msg, Toast.LENGTH_LONG).show();
                    }
                });
            }
        }
    }

    /**
     * 显示提示信息
     *
     * @param context
     * @param text
     */
    public static void showMsg(Context context, String text) {

        try {
            Toast.makeText(context, text, Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public static void showShortMsg(Context context, String text) {

        try {
            Toast.makeText(context, text, Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public static void showMsg(Context context, int resId) {

        try {
            Toast.makeText(context, resId, Toast.LENGTH_LONG).show();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    // 弹出软键盘
    public static void showSoftInput(EditText et) {
        et.setFocusable(true);
        et.setFocusableInTouchMode(true);
        et.requestFocus();
        InputMethodManager inputManager = (InputMethodManager) et.getContext()
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        inputManager.showSoftInput(et, 0);
    }

    /**
     * 获得屏幕宽度
     *
     * @param context
     * @return
     */
    public static int getScreenWidth(Context context) {
        WindowManager wm = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(outMetrics);
        return outMetrics.widthPixels;
    }

    /***
     * 根据listview的item的高度来设置listview的高度
     *
     * @param lv
     * @param adapter
     */
    public static void SetListviewHeight(ListView lv, Adapter adapter) {
        int h = 0;
        for (int i = 0; i < adapter.getCount(); i++) {
            View item = adapter.getView(0, null, lv);
            item.measure(0, 0);
            h += item.getMeasuredHeight();
        }
        int dividerH = lv.getDividerHeight();
        h += dividerH * (adapter.getCount() - 1);
        ViewGroup.LayoutParams lp = lv.getLayoutParams();
        lp.height = h;
        lv.setLayoutParams(lp);
    }

    // 将时间戳转换成会时间
    public static String GetTimeFor0(String time) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long lcc_time = Long.valueOf(time);
        String re_StrTime = sdf.format(new Date(lcc_time));
        return re_StrTime;
    }

    // /**
    // * 设置hearder属性，方便通讯中对联系人按header分类显示，以及通过右侧ABCD...字母栏快速定位联系人
    // *
    // * @param username
    // * @param user
    // */
    // public static void setUserHearder(String username, User user) {
    // String headerName = null;
    // if (!TextUtils.isEmpty(user.getNick())) {
    // headerName = user.getNick();
    // } else {
    // headerName = user.getUsername();
    // }
    // if (username.equals(Constant.NEW_FRIENDS_USERNAME)) {
    // user.setHeader("");
    // } else if (Character.isDigit(headerName.charAt(0))) {
    // user.setHeader("#");
    // } else {
    // user.setHeader(HanziToPinyin.getInstance()
    // .get(headerName.substring(0, 1)).get(0).target.substring(0,
    // 1).toUpperCase());
    // char header = user.getHeader().toLowerCase().charAt(0);
    // if (header < 'a' || header > 'z') {
    // user.setHeader("#");
    // }
    // }
    // }

    // 获得今天日期
    public static String getTodayData() {
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1;
        int day = calendar.get(Calendar.DATE);
        String yeaString = year + "";
        yeaString = yeaString.substring(yeaString.length() - 2,
                yeaString.length());
        String mString, dString;
        if (month < 10) {
            mString = "0" + month;
        } else {
            mString = month + "";
        }
        if (day < 10) {
            dString = "0" + day;
        } else {
            dString = day + "";
        }
        return yeaString + mString + dString;
    }

    // 获得明天日期
    public static String getTomoData() {
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1;
        int day = calendar.get(Calendar.DATE);
        switch (month) {
            case 1:
            case 3:
            case 5:
            case 7:
            case 8:
            case 10:
            case 12:
                if (day == 31) {
                    day = 1;
                    if (month == 12) {
                        year++;
                        month = 1;
                    } else {
                        month++;
                    }
                } else {
                    day++;
                }
                break;
            case 4:
            case 6:
            case 9:
            case 11:
                if (day == 30) {
                    day = 1;
                    if (month == 12) {
                        year++;
                        month = 1;
                    } else {
                        month++;
                    }
                } else {
                    day++;
                }
                break;
            case 2:
                if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
                    if (day == 29) {
                        day = 1;
                        if (month == 12) {
                            year++;
                            month = 1;
                        } else {
                            month++;
                        }
                    } else {
                        day++;
                    }
                } else {
                    if (day == 28) {
                        day = 1;
                        if (month == 12) {
                            year++;
                            month = 1;
                        } else {
                            month++;
                        }
                    } else {
                        day++;
                    }
                }

                break;
            default:
                break;
        }
        String yeaString = year + "";
        yeaString = yeaString.substring(yeaString.length() - 2,
                yeaString.length());
        String mString, dString;
        if (month < 10) {
            mString = "0" + month;
        } else {
            mString = month + "";
        }
        if (day < 10) {
            dString = "0" + day;
        } else {
            dString = day + "";
        }
        return yeaString + mString + dString;
    }

    // 获取后天的日期
    public static String getTheDayData() {
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1;
        int day = calendar.get(Calendar.DATE);
        switch (month) {
            case 1:
            case 3:
            case 5:
            case 7:
            case 8:
            case 10:
            case 12:
                if (day == 31) {
                    day = 2;
                    if (month == 12) {
                        year++;
                        month = 1;
                    } else {
                        month++;
                    }
                } else if (day == 30) {
                    day = 1;
                    if (month == 12) {
                        year++;
                        month = 1;
                    } else {
                        month++;
                    }
                } else {
                    day += 2;
                }
                break;
            case 4:
            case 6:
            case 9:
            case 11:
                if (day == 30) {
                    day = 2;
                    if (month == 12) {
                        year++;
                        month = 1;
                    } else {
                        month++;
                    }
                } else if (day == 29) {
                    day = 1;
                    if (month == 12) {
                        year++;
                        month = 1;
                    } else {
                        month++;
                    }
                } else {
                    day += 2;
                }
                break;
            case 2:
                if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
                    if (day == 29) {
                        day = 2;
                        if (month == 12) {
                            year++;
                            month = 1;
                        } else {
                            month++;
                        }
                    } else if (day == 28) {
                        day = 1;
                        if (month == 12) {
                            year++;
                            month = 1;
                        } else {
                            month++;
                        }
                    } else {
                        day += 2;
                    }
                } else {
                    if (day == 28) {
                        day = 2;
                        if (month == 12) {
                            year++;
                            month = 1;
                        } else {
                            month++;
                        }
                    } else if (day == 27) {
                        day = 1;
                        if (month == 12) {
                            year++;
                            month = 1;
                        } else {
                            month++;
                        }
                    } else {
                        day += 2;
                    }
                }

                break;
            default:
                break;
        }
        String yeaString = year + "";
        yeaString = yeaString.substring(yeaString.length() - 2,
                yeaString.length());
        String mString, dString;
        if (month < 10) {
            mString = "0" + month;
        } else {
            mString = month + "";
        }
        if (day < 10) {
            dString = "0" + day;
        } else {
            dString = day + "";
        }
        return yeaString + mString + dString;
    }
}
